
import React from 'react';
import { connect } from 'dva';
import { Form, Button, Table, Divider, Tag, Input, Select, Modal, TreeSelect, Tree, Transfer } from 'antd';
import AddPage from './add';
import EditPage from './edit';
import DetailPage from './detail';
import moment from "moment";
import MoButton from "components/form/MoButton";
const { Option } = Select;

// 与model建立连接
@connect(({ sysRoleModel }) => ({
  page: sysRoleModel.page,
  pageSize: sysRoleModel.pageSize,
  tabledata: sysRoleModel.tabledata,
  addShowVisible: sysRoleModel.addShowVisible,
  editShowVisible: sysRoleModel.editShowVisible,
  detailShowVisible: sysRoleModel.detailShowVisible,
  menuTreeData: sysRoleModel.menuTreeData,
  funcitonAllData: sysRoleModel.funcitonAllData
}))

//初始化Form
@Form.create()
class List extends React.PureComponent {

  state = {
    menuStatus: false,
    functionStatus: false,
    dataStatus: false,
    row_role_id: null,
    selectedMenuKeys: [],
    funcitonTargetKeys: [],
  }

  componentDidMount() {
    //初始化页面数据
    const { dispatch } = this.props;
    dispatch({
      type: 'sysRoleModel/initPageData',
      payload: {},
    });
  }

  addShow = () => {
    console.log("新增");
    const { dispatch } = this.props;
    dispatch({
      type: 'sysRoleModel/addShow',
      payload: {}
    });
  }

  editShow = (value, loadBack) => {
    console.log("编辑");
    const { dispatch } = this.props;
    dispatch({
      type: 'sysRoleModel/editShow',
      payload: { role_id: value }
    });
  }

  delRowData = (value, loadBack) => {
    console.log("删除");
    const { dispatch } = this.props;
    dispatch({
      type: 'sysRoleModel/delRowData',
      payload: { role_id: value }
    });
  }

  querySubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { dispatch } = this.props;
        dispatch({
          type: 'sysRoleModel/querySubmit',
          payload: { queryParams: values }
        });
      }
    });
  };

  /**
   * 页数据长度发生改变
   */
  pageSizeChange = (current, pageSize) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysRoleModel/pageOrPageSizeChange',
      payload: { page: 1, pageSize }
    });
  };

  /**
   * 页码发生改变
   */
  pageChange = (page, pageSize) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysRoleModel/pageOrPageSizeChange',
      payload: { page, pageSize }
    });
  };

  roleDataModelShow = (key, row_role_id) => {
    let that = this;
    const { dispatch } = this.props;
    if (key == "menuStatus") {
      dispatch({
        type: 'sysRoleModel/queryMenuByRoleId',
        payload: { role_id: row_role_id },
        callback: (retkeys) => {
          that.setState({
            [key]: true,
            row_role_id,
            selectedMenuKeys: retkeys,
            selectKey: Math.random()
          })
        }
      });
    } else if (key == "functionStatus") {
      dispatch({
        type: 'sysRoleModel/queryFunctionByRoleId',
        payload: { role_id: row_role_id },
        callback: (retkeys) => {
          that.setState({
            [key]: true,
            row_role_id,
            funcitonTargetKeys: retkeys,
            selectKey: Math.random()
          })
        }
      });
    }

  }

  selectedMenuKeysChange = (value) => {
    console.log("选中了菜单节点", value);
    this.setState({
      selectedMenuKeys: value
    })
  }

  setRoleMenu = () => {
    let that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'sysRoleModel/setRoleMenu',
      payload: { role_id: this.state.row_role_id, menus: this.state.selectedMenuKeys },
      callback: (data) => {
        that.setState({
          menuStatus: false
        })
      }
    });
  }

  selectedFunctionKeysChange = (value) => {
    console.log("选中了功能节点", value);
    this.setState({
      funcitonTargetKeys: value
    })
  }

  setRoleFunction = () => {
    let that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'sysRoleModel/setRoleFunction',
      payload: { role_id: this.state.row_role_id, functions: this.state.funcitonTargetKeys },
      callback: (data) => {
        that.setState({
          functionStatus: false
        })
      }
    });
  }

  render() {
    const { addShow, editShow, delRowData, querySubmit, pageSizeChange, pageChange, roleDataModelShow, selectedMenuKeysChange, setRoleMenu, selectedFunctionKeysChange, setRoleFunction } = this;
    const { tabledata, page, pageSize, menuTreeData, funcitonAllData } = this.props;
    const { getFieldDecorator, setFieldsValue } = this.props.form;
    const { menuStatus, dataStatus, selectedMenuKeys, selectKey, functionStatus, funcitonTargetKeys } = this.state;
    //定义数据显示项
    const columns = [{
      title: '角色名称',
      dataIndex: 'role_name',
      key: 'role_name',
      align: "center"
    }, {
      title: '权限字符',
      dataIndex: 'role_key',
      key: 'role_key',
      align: "center"
    }, {
      title: '显示顺序',
      dataIndex: 'role_sort',
      key: 'role_sort',
      align: "center"
    }, {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: "center"
    }, {
      title: '操作',
      key: 'table_id',
      render: (value, rowData, index) => (
        <span>
          <Button ghost="true" type="primary" size="small" onClick={roleDataModelShow.bind(this, "menuStatus", rowData.role_id)}>菜单权限</Button>
          <Divider type="vertical" />
          <Button ghost="true" type="primary" size="small" onClick={roleDataModelShow.bind(this, "functionStatus", rowData.role_id)}>数据权限</Button>
          <Divider type="vertical" />
          <MoButton ghost="true" type="primary" size="small" moAuto={3} moClick={(loadBack) => editShow(rowData.role_id, loadBack)}>编辑</MoButton>
          <Divider type="vertical" />
          <MoButton ghost="true" type="danger" size="small" moAuto={3} moClick={(loadBack) => delRowData(rowData.role_id, loadBack)}>删除</MoButton>
        </span>
      ),
    }]
    return (

      <div>
        <div className="flex">
          <Form layout="inline">


            <Form.Item>
              {getFieldDecorator('search', {
                valuePropName: 'value'
              })(<Input placeholder="搜索 角色名称/角色编码" allowClear ></Input>)}
            </Form.Item>
            <Form.Item label="状态">
              {getFieldDecorator('status', {
                valuePropName: 'value'
              })(<Select style={{ width: "140px" }} placeholder="选择角色状态" allowClear >
                <Option value="1">正常</Option>
                <Option value="0">停用</Option>
              </Select>)}
            </Form.Item>

            <Form.Item>
              <Button type="primary" icon="search" size="small" onClick={querySubmit}>查 询</Button>
              <Button type="primary" icon="plus" size="small" className="mgl10" onClick={addShow} >新增</Button>
            </Form.Item>
          </Form>

        </div>
        <div style={{ marginTop: "15px" }}>
          <Table rowKey="role_id" columns={columns} dataSource={tabledata.datalist} pagination={{
            "size": "small",
            "current": page,
            "pageSize": pageSize,
            "total": tabledata.totalSize,
            "showSizeChanger": true,
            "showQuickJumper": true,
            "onChange": pageChange,
            "onShowSizeChange": pageSizeChange
          }} />
        </div>
        <div>
          <AddPage></AddPage>
          <EditPage></EditPage>
          <DetailPage></DetailPage>
        </div>
        <Modal
          width="700px"
          title="--数据权限"
          visible={functionStatus}
          onOk={() => {
            setRoleFunction();
          }}
          onCancel={() => {
            this.setState({
              functionStatus: false
            })
          }}
        >
          <div style={{ width: "100%" }} className="centerXY">
            <Transfer key={selectKey}
              dataSource={funcitonAllData}
              targetKeys={funcitonTargetKeys}
              showSearch
              render={item => item.title}
              listStyle={{
                width: 250,
                height: 300,
              }}
              operations={['添加', '移除']}
              onChange={selectedFunctionKeysChange}
            ></Transfer>
          </div>
        </Modal>
        <Modal
          width="500px"
          bodyStyle={{height:"350px",overflow:"auto"}}
          title="--菜单权限"
          visible={menuStatus}
          onOk={() => { setRoleMenu() }}
          onCancel={() => {
            this.setState({
              menuStatus: false
            })
          }}
        >
          <div>
            <Tree key={selectKey} treeData={menuTreeData} showLine={true} checkable defaultCheckedKeys={selectedMenuKeys} onCheck={selectedMenuKeysChange} />
          </div>
        </Modal>
      </div>

    );
  }
}

export default List;
